<?php
/**
 * Created by xun at 2020/5/11
 */

namespace app\storage;


use app\module\websocket\WebSocketAction;

class Db
{
    use Singleton;

    public function __construct()
    {
        // $this->pool = new MysqlPool();
        // $this->pool->settal();
        // $conn = $this->conn->getConnection();
        // if (!$this->conn) {
        //     echo "get conn error.\n";
        //     return;
        // }
        // $this->conn = $conn;
    }

    public function insert($toUser, $currentUser, $params, $is_read = 0)
    {
        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        $date = date('Y-m-d H:i:s', time());
        $sql = "INSERT INTO `zx_wx_chat_history` (
                    `session_id`,
                    `to_userid`,
                    `to_nickname`,
                    `to_openid`,
                    `to_avatar`,
                    `from_userid`,
                    `from_nickname`,
                    `from_openid`,
                    `from_avatar`,
                    `from_tel`,
                    `src_id`,
                    `src_type`,
                    `content`,
                    `is_read`,
                    `created_at`,
                    `updated_at`
                )
                VALUES
                    (
                        {$params['session_id']},
                        {$toUser['user_id']},
                        '{$toUser['username']}',
                        '{$toUser['openid']}',
                        '',
                        '{$currentUser['user_id']}',
                        '{$currentUser['username']}',
                        '{$currentUser['openid']}',
                        '',
                        NULL,
                        {$params['src_id']},
                        {$params['src_type']},
                        '{$params['message']}',
                        {$is_read},
                        '{$date}',
                        NULL
                    );";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo "insert row error.\n";
            echo $mysqli->error . "\n";
        }
        $pool->free($mysqli);
    }

    public function getHistory($params)
    {
        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        $sql = "SELECT * FROM `zx_wx_chat_history` ch WHERE ch.`session_id` = '{$params['session_id']}'
        ORDER BY ch.`created_at` ASC";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo "get history error.\n";
            echo $mysqli->error . "\n";
        }
        $pool->free($mysqli);
        $list = [];
        while ($row = $r->fetch_assoc()) {
            $list[] = $row;
        }
        return $list;
    }

    public function getUser($openid)
    {
        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        if (!$mysqli) {
            echo "get conn error.\n";
            return;
        }
        $sql = "SELECT * FROM `zx_user_auth` ua WHERE ua.`openid` = '{$openid}' LIMIT 1";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo $mysqli->error . "\n";
        }
        $pool->free($mysqli);
        $result = null;
        while ($row = $r->fetch_assoc()) {
            $result = $row;
        }
        return $result;
    }

    public function getWxUser($openid)
    {
        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        if (!$mysqli) {
            echo "get conn error.\n";
            return;
        }
        $sql = "SELECT * FROM `57sy_common_user` cu WHERE cu.`openid` = '{$openid}' LIMIT 1";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo $mysqli->error . "\n";
        }
        $result = null;
        $rows = $r->fetch_array();
        if (empty($rows)) {
            $sql = "SELECT * FROM `zx_user_auth` ua WHERE ua.`openid` = '{$openid}' LIMIT 1";
            $r = $mysqli->query($sql);
            if (!$r) {
                echo $mysqli->error . "\n";
            }
            while ($row = $r->fetch_assoc()) {
                $result = [
                    'username' => $row['nickname'],
                    'avatar' => $row['headurl'],
                    'mobile_number' => '',
                    'openid' => $row['openid'],
                ];
            }
            return $result;
        } else {
            $result = [
                'username' => $rows['nickname'],
                'avatar' => $rows['headimgurl'],
                'mobile_number' => $rows['tel'],
                'openid' => $rows['openid'],
            ];
        }
        $pool->free($mysqli);
        return $result;
    }

    public function createSession($server, $client)
    {
        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        $result = null;
        $sql = "SELECT * FROM `zx_wx_session` s WHERE s.`server_openid` = '{$server['openid']}'
                AND s.`client_openid` = '{$client['openid']}'
                LIMIT 1;";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo $mysqli->error . "\n";
            throw new \Exception($mysqli->error);
        }
        $rows = $r->fetch_array();
        if (empty($rows)) {
            $date = date('Y-m-d H:i:s', time());
            $sql = "INSERT INTO `zx_wx_session` (
                    `server_id`,
                    `server_openid`,
                    `client_id`,
                    `client_openid`,
                    `key`,
                    `created_at`,
                    `updated_at`
                )
                VALUES
                    (
                        {$server['user_id']},
                        '{$server['openid']}',
                        {$client['user_id']},
                        '{$client['openid']}',
                        '',
                        '{$date}',
                        NULL
                    );";
            $mysqli->query($sql);
            $result = [
                'id' => $mysqli->insert_id,
                'server_id' => $server['user_id'],
                'server_openid' => $server['openid'],
                'client_id' => $client['user_id'],
                'client_openid' => $client['openid'],
            ];
        } else {
            $result = $rows;
        }
        $pool->free($mysqli);
        return $result;
    }

    public function getSessions($server_openid)
    {
        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        $result = [];
        $sql = "SELECT * FROM `zx_wx_session` s WHERE s.`server_openid` = '{$server_openid}';";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo $mysqli->error . "\n";
        }
        while ($row = $r->fetch_assoc()) {
            $result[] = $row;
        }
        $pool->free($mysqli);
        return $result;
    }

    public function getTemplateParams() {
        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        $sql = "SELECT * FROM `zx_wx_send_template_parameter` tp
        LEFT JOIN `zx_wx_send_template_setting` ts ON tp.send_id = ts.send_id WHERE 
        ts.`send_code` = 'sys_offline' AND ts.`is_delete` = 0;";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo $mysqli->error . "\n";
        }
        $result = [];
        while ($row = $r->fetch_assoc()) {
            $result[] = $row;
        }
        $pool->free($mysqli);
        return $result;
    }

    public function getQuickMessage($user_type)
    {
        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        $sql = "SELECT * FROM `zx_wx_quick_msg` qm WHERE qm.`type` = '{$user_type}' AND qm.`status` = 1;";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo $mysqli->error . "\n";
        }
        $result = [];
        while ($row = $r->fetch_assoc()) {
            $result[] = $row;
        }
        $pool->free($mysqli);
        return $result;
    }

    public function getSrc($src_id, $src_type)
    {
        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        $sql = "SELECT * FROM `website_common_info` ci WHERE ci.`id` = '{$src_id}' LIMIT 1;";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo $mysqli->error . "\n";
        }
        $result = null;
        while ($row = $r->fetch_assoc()) {
            $result = $row;
        }
        $pool->free($mysqli);
        return $result;
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        // var_dump('__destruct');
        // $this->pool->free($this->conn);
    }

}